package org.jeecg.modules.employee.controller;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.employee.entity.Employee;
import org.jeecg.modules.employee.entity.EmployeeTree;
import org.jeecg.modules.employee.service.IEmployeeService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.uniubi.controller.UniController;
import org.jeecg.modules.uniubi.controller.ApiUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 员工信息表
 * @Author: jeecg-boot
 * @Date:   2025-01-16
 * @Version: V1.0
 */
@Api(tags="员工信息表")
@RestController
@RequestMapping("/employee/employee")
@Slf4j
public class EmployeeController extends JeecgController<Employee, IEmployeeService> {
	@Autowired
	private IEmployeeService employeeService;
	@Autowired
	private ISysDepartService sysDepartService;
	 @Autowired
	 private UniController uniUbi;
	 @Autowired
	 private ApiUtil apiUtil;
	
	/**
	 * 分页列表查询
	 *
	 * @param employee
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="员工信息表-分页列表查询", notes="员工信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(Employee employee,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Employee> queryWrapper = QueryGenerator.initQueryWrapper(employee, req.getParameterMap());
		Page<Employee> page = new Page<Employee>(pageNo, pageSize);
		IPage<Employee> pageList = employeeService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @ApiOperation(value="大屏-中间饼图1", notes="大屏-中间饼图1")
	 @GetMapping(value = "/m/getCenter1")
	 public Result<?> getCenter1() {
		List<Map<String, Object>> list = employeeService.getCenter1();
		 return Result.OK(list);
	 }

	 @ApiOperation(value="大屏-echarts左3", notes="大屏-echarts左3")
	 @GetMapping(value = "/m/getLeft3")
	 public Result<?> getLeft3() {
		 List<Map<String, Object>> list = employeeService.getLeft3();
		 return Result.OK(list);
	 }

	 @ApiOperation(value="员工信息表-获取树结构", notes="员工信息表-获取树结构")
	 @GetMapping(value = "/treeList")
	 public Result<?> treeList() {
		 List<SysDepartTreeModel> sysDepartTreeModels = sysDepartService.queryTreeList();
		 List<EmployeeTree> employeeTrees = new ArrayList<>();
		 for (SysDepartTreeModel sysDepartTreeModel : sysDepartTreeModels) {
			 EmployeeTree rootEmployeeTree = buildEmployeeTree(sysDepartTreeModel);
			 employeeTrees.add(rootEmployeeTree);
		 }
		 return Result.OK(employeeTrees);
	 }

	 private EmployeeTree buildEmployeeTree(SysDepartTreeModel model) {
		 EmployeeTree employeeTree = new EmployeeTree();
		 employeeTree.setKey(model.getKey());
		 employeeTree.setTitle(model.getTitle());
		 employeeTree.setChildren(new ArrayList<>());
		 // 如果当前节点有子节点，则递归地为每个子节点创建EmployeeTree
		 if (model.getChildren() != null && !model.getChildren().isEmpty()) {
			 for (SysDepartTreeModel child : model.getChildren()) {
				 EmployeeTree childEmployeeTree = buildEmployeeTree(child); // 递归调用
				 employeeTree.getChildren().add(childEmployeeTree);
				 // 添加员工到最邻近的部门下
				 String id = child.getId();
				 List<Employee> employees = employeeService.listByDeptIds(id);
				 if (!employees.isEmpty()){
					 childEmployeeTree.setCheckable(true).setSelectable(true);
					 for (Employee employee : employees) {
						 EmployeeTree employeeNode = new EmployeeTree();
						 employeeNode.setKey(employee.getAdmitGuid());
						 employeeNode.setTitle(employee.getName());
						 employeeNode.setChildren(null); // 员工节点没有子节点
						 employeeNode.setCheckable(true).setSelectable(true);
						 childEmployeeTree.getChildren().add(0, employeeNode);
					 }
				 }
			 }
		 }
		 return employeeTree;
	 }
	
	/**
	 *   添加
	 *
	 * @param employee
	 * @return
	 */
	@AutoLog(value = "员工信息表-添加")
	@ApiOperation(value="员工信息表-添加", notes="员工信息表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody Employee employee) {
		addSelect(employee.getIdCardNo(),employee.getName());
		uniUbi.selectOne(employee);//注册前查询
		employeeService.save(employee);
		JSONObject result = uniUbi.add(employee);//添加主体
		if (result != null && result.getBoolean("success")) {
//			employee.setAdmitGuid(result.getJSONObject("data").getString("admitGuid"));
//			employee.setStatus("1");
//			apiUtil.authorization(DateUtils.formatDate(employee.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
			return Result.OK("添加成功！");
		}
		return Result.error("添加失败!");
	}

	 @AutoLog("添加前查询")
	 @ApiOperation(value = "添加前查询",notes = "添加前查询")
	 @GetMapping("addSelect")
	 public void addSelect(String idCardNo,String name){
		 QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("name",name);
		 queryWrapper.eq("id_card_no",idCardNo);
		 queryWrapper.orderByDesc("create_time");

		 List<Employee> list = employeeService.list(queryWrapper);
		 if (!list.isEmpty()){
			 Employee personnelRegistration = list.get(0);
			 uniUbi.delete(personnelRegistration.getAdmitGuid());
		 }
	 }

	 @ApiOperation(value = "员工信息表-根据名字查询",notes = "员工信息表-根据名字查询")
	 @GetMapping("/getByName")
	 public Result<?> getByName(@RequestParam(name = "name") String name){
		 LambdaQueryWrapper<Employee> wrapper = Wrappers.lambdaQuery();
		 wrapper.eq(Employee::getName,name);
		 List<Employee> list = employeeService.list(wrapper);
		 if (!list.isEmpty()){
			 return Result.OK(list.get(0));
		 } else {
			 return Result.OK();
		 }
	 }
	
	/**
	 *  编辑
	 *
	 * @param employee
	 * @return
	 */
	@AutoLog(value = "员工信息表-编辑")
	@ApiOperation(value="员工信息表-编辑", notes="员工信息表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody Employee employee) {
		employeeService.updateById(employee);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "员工信息表-通过id删除")
	@ApiOperation(value="员工信息表-通过id删除", notes="员工信息表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		employeeService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "员工信息表-批量删除")
	@ApiOperation(value="员工信息表-批量删除", notes="员工信息表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.employeeService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="员工信息表-通过id查询", notes="员工信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Employee employee = employeeService.getById(id);
		if(employee==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(employee);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param employee
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Employee employee) {
        return super.exportXls(request, employee, Employee.class, "员工信息表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
				long start = System.currentTimeMillis();
				employeeService.saveBatch(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
    }

}
